/*
 * 如果是被包含的文件，尽量选择为.hpp而非.cpp，否则可能陷入重复包含
 * */

#include "13_EchoServer.hpp"
#include "15_DefaultMessageHandler.hpp"
#include "15_Mytask.hpp"
#include <iostream>
#include <csignal>

#define info_msg(msg) do { \
    printf("%s | %d | %s | %s \n", __FILE__, __LINE__, __FUNCTION__, msg); \
} while(0)

namespace xy
{
// 声明一个外部变量来访问服务器实例
//xy::TcpServer* g_server = nullptr;
Echo_Server* Echo_Server::_instance = nullptr;

Echo_Server::Echo_Server(unsigned short port, const std::string& ip, int thread_num, int que_size)
    :_tcpserver(port, ip)
    ,_thread_pool(thread_num, que_size)
    ,_default_handler(std::make_shared<DefaultMessageHandler>())
    ,_mytask_handler(std::make_shared<Mytask>())    // 基类指针指向派生类，走多态
    ,_is_running(false)
    {
        _instance = this;   // 设置实例指针
    }

void Echo_Server::start()
{
    if(_is_running == true)
    {
        info_msg("Start failure: Echo_Server is already running.");
        return;
    }
    signal(SIGINT, signal_handler);  // 注册信号处理函数
    _thread_pool.start();

    //设置回调函数
    _tcpserver.get_event_loop().set_connection_callback(std::bind(&Echo_Server::on_connection, this, std::placeholders::_1));
    _tcpserver.get_event_loop().set_message_callback(std::bind(&Echo_Server::on_message, this, std::placeholders::_1, std::placeholders::_2));
    _tcpserver.get_event_loop().set_close_callback(std::bind(&Echo_Server::on_close, this, std::placeholders::_1));

    _tcpserver.start();
    _is_running = true;
}

void Echo_Server::stop()
{
    if(_is_running == false)
    {
        info_msg("Stop failure: Echo_Server has already stopped.");
        return;
    }

    _thread_pool.stop();
    _tcpserver.stop();
    _is_running = false;

}

// 处理ctrl + c信号，优雅退出
void Echo_Server::signal_handler(int signum)
{
    if(_instance)
    {
        info_msg("Received signal, server shutting down...");
        _instance->stop();
    }
    else{
        info_msg("_instance not exist.");
    }
    //exit(0);      // 移出exit(0)调用，因为在TcpServer::stop()中已经准备关闭代码
}

// 定义回调函数
void Echo_Server::on_connection(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "New connection established: " << conn->tostring() << "\n";
    
    // 默认分配第一个处理器
    _conn_to_handler[conn->get_fd()] = _default_handler;

    conn->send("Please enter 'SWITCH 1' for Default handler or 'SWITCH 2' for MyTask handler.");
}

// 内部方法：将消息处理调度到线程池
void Echo_Server::on_message(const TCPconnection::TCPconnectionPtr& conn, const std::string &msg)
{
    // 记录接收到的消息
    std::cout << "Received message:\n " << conn->tostring() << ":" << msg << std::endl;

    // 检查是否是切换处理器的命令(格式为："SWITCH 1" 或 "SWITCH 2")
    if(msg.substr(0, 6) == "SWITCH")
    {
        if(msg.size() >= 8)
        {
            int handler_type = std::stoi(msg.substr(7));    // 取出第7位数据
            if(handler_type == 1)
            {
                _conn_to_handler[conn->get_fd()] = _default_handler;
                conn->send("Switched to Default handler\n");
                info_msg("Connection switched to Default handler");
            }
            else if(handler_type == 2)
            {
                _conn_to_handler[conn->get_fd()] = _mytask_handler;
                conn->send("Switched to Mytask handler\n");
                info_msg("Connection switched to Mytask handler");
            }
            else
            {
                conn->send("Invalid command format. Use 'SWITCH 1' or 'SWITCH 2'\n");
            }

        }
            return;
    }

    // 使用当前连接的处理器处理消息
    auto it = _conn_to_handler.find(conn->get_fd());
    if(it != _conn_to_handler.end())
    {
        _thread_pool.addTask(
            [this, conn, msg, handler = it->second](){
                // 在线程池中使用分配的任务处理器处理消息
                std::string response = handler->handle(msg);
                // 发送响应
                conn->send(response);
            }
        );
    }
    else
    {
        _thread_pool.addTask(
            [this, conn, msg](){
                // 在线程池中使用分配的任务处理器处理消息
                std::string response = _default_handler->handle(msg);
                // 发送响应
                conn->send(response);
            }
        );
    }
}

void Echo_Server::on_close(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "Connection closed: " << conn->tostring() << "\n";

    // 移除连接到处理器的映射
    _conn_to_handler.erase(conn->get_fd());
}
    
// 默认消息的实现（用户可以重写）
std::string Echo_Server::handle_message1(const std::string& msg)
{
    return _default_handler->handle(msg);
}

std::string Echo_Server::handle_message2(const std::string& msg)
{
    return _mytask_handler->handle(msg);
}

}

